package com.md.api.controller;

import com.md.api.common.utils.DateUtils;
import com.md.api.common.utils.FaceRecognitionUtil;
import com.md.api.common.utils.FileProperties;
import com.md.api.common.utils.StringUtils;
import com.md.api.dao.PhotoInfoMapper;
import com.md.api.dao.PictureInfoMapper;
import com.md.api.entity.HttpResult;
import com.md.api.entity.PhotoInfo;
import com.md.api.entity.PictureInfo;
import com.md.api.entity.util.SearchFaceResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author liujie
 * @ClassName FaceController
 * @Date 2022年11月01日14:01
 **/

@Slf4j
@RequestMapping("/face")
@RestController
public class FaceController {
    @Resource
    PhotoInfoMapper photoMapper;
    @Resource
    PictureInfoMapper pictureMapper;
    @Autowired
    FileProperties properties;
    @Value("${downUrl}")
    public String downUrl;
    @Value("${fileName}")
    public String fileName;

    @PostMapping("/getSign")
    @ResponseBody
    public HttpResult getSign(@RequestBody Map<String, String> params) {
        try {
            String sign = FaceRecognitionUtil.getSign(params);
            return new HttpResult(sign);
        } catch (Exception e) {
            log.error("上传失败", e);
            return HttpResult.fail(e.getMessage());
        }
    }

    /**
     * 人脸识别
     */
    @PostMapping("/searchFace")
    @ResponseBody
    public HttpResult searchFace(HttpServletRequest request,MultipartFile file) {
        if (StringUtils.isEmpty(request.getHeader("photoId"))){
            return HttpResult.PARAM_ERROR;
        }
        try {
            String photoId = request.getHeader("photoId");
            String language = request.getHeader("language");
            PhotoInfo dbPhoto = photoMapper.getByPhotoId(photoId);
            if (null!=dbPhoto&&dbPhoto.getStatus()==-1){
                if(StringUtils.isNotEmpty(language)&&language.equals("en")){
                    return HttpResult.fail("This album is frozen. Please contact the photographer to renew the membership or the administrator to unfreeze it");
                }
                return HttpResult.fail("該相冊處於冷凍中，請聯係攝影師續費會員或管理員解凍！");
            }
            if (null!=dbPhoto&&dbPhoto.getValidDate().getTime()<new Date().getTime()){
                if(StringUtils.isNotEmpty(language)&&language.equals("en")){
                    return HttpResult.fail("The photo album activity time has passed and this feature is currently not supported");
                }
                return HttpResult.fail("相冊活動時間已過，暫不支持此功能！");
            }
            if (null!=dbPhoto&&DateUtils.add(new Date(), Calendar.DATE,-30).getTime()>dbPhoto.getCreateTime().getTime()){
                if(StringUtils.isNotEmpty(language)&&language.equals("en")){
                    return HttpResult.fail("This feature is not supported after 30 days of album creation");
                }
                return HttpResult.fail("相冊創建30天后不支持此功能！");
            }
            List<SearchFaceResult> result = new ArrayList<>();
            Integer faceCount = FaceRecognitionUtil.detectFace(file);
            log.info("识别到的人脸数量："+faceCount);
            if (faceCount<1) {
                if(StringUtils.isNotEmpty(language)&&language.equals("en")){
                    return HttpResult.fail("Please upload a facial image");
                }
                return HttpResult.fail("請上傳人臉圖片！");
            }
            List<SearchFaceResult> searchResult = FaceRecognitionUtil.searchFace(dbPhoto.getFaceDbId(), file);
            if (null==searchResult){
                if(StringUtils.isNotEmpty(language)&&language.equals("en")){
                    return HttpResult.fail("Please upload a facial image");
                }
                return HttpResult.fail("請上傳人臉圖片！");
            }
            for (SearchFaceResult faceResult:searchResult){
                PictureInfo byPictureId = pictureMapper.getByPictureId(faceResult.getEntityId());
                if (null!=byPictureId&&byPictureId.getPhotoId().equals(photoId)){
                    result.add(faceResult);
                }
            }
            return new HttpResult(result);
        } catch (Exception e) {
            log.error("上传失败", e);
            return HttpResult.fail(e.getMessage());
        }
    }

    /**
     * 文件上传请求
     */
    @PostMapping("/detectLiving")
    @ResponseBody
    public HttpResult detectLiving(HttpServletRequest request,MultipartFile file) {
        try {
            Integer aBoolean = FaceRecognitionUtil.detectFace(file);

            System.out.println("detectLivingFace:"+aBoolean);
            return new HttpResult(aBoolean);
        } catch (Exception e) {
            log.error("上传失败", e);
            return HttpResult.fail(e.getMessage());
        }
    }

}
